package com.nowcoder.community.actuator;

import com.nowcoder.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author TwfPlayer
 * @date 2023/8/23 18:42
 * @description: TODO
 */
@Component
@Endpoint(id = "database")//为端点取名,通过该id访问
public class DatabaseEndpoint {

    private static final Logger logger = LoggerFactory.getLogger(DatabaseEndpoint.class);

    @Autowired
    private DataSource dataSource;

    //通过Get请求访问
    @ReadOperation
    public String checkConnection(){
        try (
                //在此处,连接可以被自动关闭
                Connection connection = dataSource.getConnection();
                ){
            return CommunityUtil.getJSONString(0,"获取连接成功!");
        } catch (SQLException e) {
            logger.error("获取连接失败:"+e.getMessage());
            return CommunityUtil.getJSONString(1,"获取连接失败!");
        }
    }
}
